package com.wx.mp.controller;


import com.alibaba.fastjson.JSONObject;
import com.wx.mp.domain.TCarOp;
import com.wx.mp.utils.*;
import com.wx.mp.utils.exception.BizException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BizController {
	private static final String MIME_JSON = "application/json;charset=UTF-8";
	@Autowired
	private HttpSession session;
	
	/**
	 * 返回jqgrid格式数据
	 * @param bizResult
	 * @param voClass
	 */
	protected <DTO,VO> BizResultVO<EasyUIDataGridVO<VO>> returnJqGridData(BizResult<PageBean<DTO>> bizResult, Class<VO> voClass) throws InstantiationException, IllegalAccessException {
		PageBean<DTO> pageBean = getBizResultData(bizResult);
		//将DTO转换为VO
		List<VO> vos = new ArrayList<>();
		if(!CollectionUtils.isEmpty(pageBean.getDataList())){
			for (DTO dto : pageBean.getDataList()) {
				VO vo = voClass.newInstance();
				BeanUtils.copyProperties(dto, vo);
				vos.add(vo);
			}
		}
		//返回jqGrid数据
		EasyUIDataGridVO<VO> jqGridDatas = new EasyUIDataGridVO<>();
		jqGridDatas.setTotal(pageBean.getPageTotals()==null?0:pageBean.getPageTotals());
		jqGridDatas.setRows(vos);
		
		BizResultVO<EasyUIDataGridVO<VO>> bizResultVO = new BizResultVO<>();
		bizResultVO.setCode(bizResult.getErrCode().getCode());
		bizResultVO.setMsg(bizResult.getErrMsg());
		bizResultVO.setData(jqGridDatas);
		
		return bizResultVO;
	}
	
	/**
	 * 返回jqgrid格式数据
	 */
	protected <DTO> BizResultVO<EasyUIDataGridVO<DTO>> returnJqGridData(BizResult<PageBean<DTO>> bizResult) {
		PageBean<DTO> pageBean = getBizResultData(bizResult);
		//返回jqGrid数据
		EasyUIDataGridVO<DTO> jqGridDatas = new EasyUIDataGridVO<>();
		jqGridDatas.setTotal(pageBean.getPageTotals()==null?0:pageBean.getPageTotals());
		jqGridDatas.setRows(pageBean.getDataList());
		
		BizResultVO<EasyUIDataGridVO<DTO>> bizResultVO = new BizResultVO<>();
		bizResultVO.setCode(bizResult.getErrCode().getCode());
		bizResultVO.setMsg(bizResult.getErrMsg());
		bizResultVO.setData(jqGridDatas);
		
		return bizResultVO;
	}
	/**
	 * 分页结果封装后返回标准格式JSON串.<br/>
	 * @param response
	 * @param result
	 */
	@SuppressWarnings("unused")
	public  void returnJsonDataGrid(HttpServletResponse response, BizResult<?>  result){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		if(result == null){
			throw new NullPointerException("result 为空,不能进行封装!");
		}else if(result.getData() == null){
			throw new NullPointerException("pageBean 为空,不能进行封装!");
		}else{
			 if(result.getData() instanceof PageBean<?>) {
				 PageBean<?> pageBean = (PageBean<?>)result.getData();
					Map<String,Object> map = new HashMap<String,Object>();
					map.put("total", (null ==pageBean.getPageTotals()? 0 :pageBean.getPageTotals()));
					map.put("rows", pageBean.getDataList() != null ? pageBean.getDataList() :new ArrayList<Object>() );
					resultMap.put("code", result.getErrCode().getCode());
					resultMap.put("msg", result.getErrMsg());
					resultMap.put("data", map);
				
			}else{
				throw new ClassCastException("result.getData() 类型转换异常");
			}
			
		}
		this.returnJson(response, resultMap);
	}
	
	/**
	 * 
	 * @param data
	 */
	public <VO> BizResultVO<EasyUIDataGridVO<VO>> returnGridData4JqGrid(List<VO> data,Integer totalCount) {
		//返回jqGrid数据
		EasyUIDataGridVO<VO> jqGridDatas = new EasyUIDataGridVO<>();
		jqGridDatas.setTotal(totalCount==null?0:totalCount);
		jqGridDatas.setRows(data);
		
		BizResultVO<EasyUIDataGridVO<VO>> bizResultVO = new BizResultVO<>();
		bizResultVO.setCode(ErrorType.BIZ_SUCCESS.getCode());
		bizResultVO.setMsg(ErrorType.BIZ_SUCCESS.getMsg());
		bizResultVO.setData(jqGridDatas);
		return bizResultVO;
	}
	/**
	 * 获取返回的数据
	 */
	public <T> T getBizResultData(BizResult<T> bizResult){
		//有异常，抛出
		if(!bizResult.isSuccess() || !bizResult.getErrCode().getCode().equals(ErrorType.BIZ_SUCCESS.getCode())){
			throw new BizException(bizResult.getErrCode(),bizResult.getErrMsg());
		}
		return bizResult.getData();
	}
	/**
	 * 返回JSon格式的数据
	 */
	public String returnJson(HttpServletResponse response, Object data) {
		
		return returnText(response, JSONObject.toJSONString(data), MIME_JSON);
	}
	
	/**
	 * 返回xml格式的数据
	 *
	 * @param response
	 * @param text
	 * @throws Exception
	 */
	public String returnXml(HttpServletResponse response, CharSequence text) {
		return returnText(response, text, "text/xml;charset=UTF-8");
	}

	/**
	 * 返回文本数据
	 * @param response
	 * @param text
	 * @param contenttype 内容类型，如：text/plain、text/xml、application/json、text/json、text/javascript、application/javascript（不支持旧浏览器）
	 * @param encoding 字符集编码，如：GB18030、UTF-8，不建议使用GB2312和GBK
	 * @throws Exception
	 */
	public String returnText(HttpServletResponse response, CharSequence text, final String contenttype, final String encoding) {
		return returnText(response, text, contenttype+";charset="+encoding);
	}

	/**
	 * 返回文本数据
	 *
	 * @param response
	 * @param text
	 * @param contenttype
	 */
	public String returnText(HttpServletResponse response, CharSequence text, final String contenttype) {
		response.setContentType(contenttype);
		if (text != null) {
			try {
				response.getWriter().write(text.toString());
			} catch (IOException e) {
				throw new BizException(ErrorType.BIZ_ERROR,e);
			}
		}
		return null;
	}

	/**
	 * 设置文件头格式
	 * @param response
	 * @param mimeType
	 * @param fileName
	 * @param size
	 */
	public void setFileHeader(HttpServletResponse response, CharSequence mimeType,
                              final CharSequence fileName, int size) {
		response.reset();
		// 设置response的Header
		if(mimeType != null){
			response.setContentType(mimeType.toString()) ;
		}
		try {
			response.addHeader("Content-Disposition","attachment;filename=" + new String(fileName.toString().getBytes("GB18030"),"ISO-8859-1")) ;
		} catch (UnsupportedEncodingException e) {
			throw new BizException(ErrorType.BIZ_ERROR,"文件名编码转换失败") ;
		}
		if(size > 0){
			response.addIntHeader("Content-Length", size) ;
		}
	}

	/**
	 * 设置浏览器返回类型为Excel文件
	 * @param response
	 * @param mimeType
	 * @param fileName
	 * @param size
	 */
	public void setExcelFileHeader(HttpServletResponse response, CharSequence mimeType,
                                   final CharSequence fileName, int size) {
		setFileHeader(response, "application/vnd.ms-excel", fileName, size);
	}
	/**
	 * 文件下载
	 * @param response
	 * @param mimeType
	 * @param fileName
	 * @param file
	 * @param size
	 */
	public void downloadFile(HttpServletResponse response, CharSequence mimeType,
                             final CharSequence fileName, InputStream file, int size) {
		setFileHeader(response, mimeType, fileName, size) ;
		try {
			OutputStream out = response.getOutputStream() ;
			int l ;
			while((l=file.read()) >= 0){
				out.write(l) ;
			}
			out.flush() ;
		} catch (IOException e) {
			throw new BizException(ErrorType.BIZ_ERROR,"下载文件失败") ;
		}finally {
				if (null != file) {
					try {
						file.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

		}
	}
	
	
	
	
	
	/**
	 * 返回jqgrid格式数据
	 * @param bizResult
	 * @param voClass
	 * @return
	 */
	protected <DTO,VO> BizResultVO<EasyUIDataGridVO<VO>> returnJqGridDataByList(BizResult<List<DTO>> bizResult,int total,Class<VO> voClass) throws InstantiationException, IllegalAccessException {
		//List<DTO> pageBean = getBizResultData(bizResult);
		//将DTO转换为VO
		List<VO> vos = new ArrayList<>();
		if(!CollectionUtils.isEmpty(bizResult.getData())){
			for (DTO dto : bizResult.getData()) {
				VO vo = voClass.newInstance();
				BeanUtils.copyProperties(dto, vo);
				vos.add(vo);
			}
		}
		//返回jqGrid数据
		EasyUIDataGridVO<VO> jqGridDatas = new EasyUIDataGridVO<>();
		
		jqGridDatas.setTotal(total);
		jqGridDatas.setRows(vos);
		
		BizResultVO<EasyUIDataGridVO<VO>> bizResultVO = new BizResultVO<>();
		bizResultVO.setCode(bizResult.getErrCode().getCode());
		bizResultVO.setMsg(bizResult.getErrMsg());
		bizResultVO.setData(jqGridDatas);
		
		return bizResultVO;
	}


	protected TCarOp getOpInfoBySession(){
		return (TCarOp)session.getAttribute("userInfo");
	}

	protected  void setOpInfoToSession(TCarOp carOp){
		session.setAttribute("userInfo",carOp);
	}
}
